import Request from '~/modules/@wmeimob/request/src/taro/index';
import * as config from '~/config';
import * as Taro from '@tarojs/taro';
import { merge } from '~/modules/@wmeimob/decorator/src/components';
import { RequestEventEnum, IData, IRequestOption } from '~/modules/@wmeimob/request/src/const';

interface API {
  APIGet: any,
  APIPost: any
  APIPut: any,
  APIDelete: any,
}

const { get, post, del, put, request, requestObj } = new Request<API>(config);
export { get, post, del, put, request };

class RequestFunction {
  @merge()
  static async getToken() {
    const { code } = await Taro.login();
    return get(config.silentAuthorizationUrl as any,
      { code }, {
      unWillSend: true
    });
  }

  /**
   * 请求发送开始 可修改请求参数
   *
   * @export
   * @param {(Taro.request.Param<string | any>)} params
   */
  static async requestWillMount(params: Taro.request.Option<string | any>) {
    let token = Taro.getStorageSync('token');

    if (!token) {
      if (config.silentAuthorization) {
        // 静默授权
        const { content: { token: DataToken, openid } } = await RequestFunction.getToken();
        // 赋值token
        token = DataToken;
        Taro.setStorageSync('token', token);
        Taro.setStorageSync('openid', openid);
      } else {
        Taro.navigateTo({
          url: config.loginUrl
        });
      }
    }

    params.header = {
      ...params.header,
      Authorization: token
    };
  }

  /**
   * 请求发送结束
   *
   * @static
   * @memberof RequestFunction
   */
  static async requestDidMount(response: Taro.request.SuccessCallbackResult, params: {
    url: string, data: IData | string, options: IRequestOption
  }) {
    if (response.data) {
      switch (response.data.code) {
        case 401:
          Taro.setStorageSync('token', '');

          if (config.silentAuthorization) {
            const res = await requestObj.request<any>(params.url, params.data, params.options);
            return res;
          }

          Taro.navigateTo({
            url: config.loginUrl
          });
          break;
      }
    }
  }
}

requestObj.eventEmitter.addListener(RequestEventEnum.WillSend, RequestFunction.requestWillMount);
requestObj.eventEmitter.addListener(RequestEventEnum.DidMount, RequestFunction.requestDidMount as any);

